/**
 * 
 */
package com.hw.hcit.feature;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;

import com.hw.hcit.R;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.storage.StorageManager;
import android.provider.Settings;
import android.text.format.Formatter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.os.storage.StorageManager;
import android.os.storage.StorageEventListener;
import android.os.storage.DiskInfo;
import android.os.storage.VolumeInfo;
import com.hw.hcit.conf.Config;
import com.hw.hcit.conf.JCtrlCallback;
import com.hw.hcit.conf.JTestItem;
import com.goodix.share.*;
/**
 * @author gaoshengpan
 *
 */
public class TpTestItem extends JTestItem {
	TextView mTestResult;
    private boolean powerClicked = false;
    private String TAG = "TpTestItem";
    private Button mButton1,mButton2;
    private VolumeInfo mVolume;
    private List<VolumeInfo> volumes;
    private static String SD_CARD_PATH = "storage/";;
    private StorageManager mStorageManager;
    private Context mContext;
    private Handler mHandler = new Handler() {

        @Override
	public void handleMessage(Message msg) {
		// TODO Auto-generated method stub
		super.handleMessage(msg);
		if(msg.arg1 == R.string.tp_pass){
			mTestResult.setText(getString(R.string.tp_pass));
            mTestResult.setTextColor(Color.GREEN);
            mButton1.setEnabled(true);
		}else {
			mTestResult.setText(getString(R.string.tp_fail));
            mTestResult.setTextColor(Color.RED);
            mButton2.setEnabled(true);
		
		}
	}
    };
    /*15-12-09 gaoshenpan  hide navigationbar begin*/
    public void hideNavigationBar() {
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
            | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar

        if( android.os.Build.VERSION.SDK_INT >= 19 ){ 
            uiFlags |= 0x00001000;    //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        Config.GetActivity().getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }
    /*15-12-09 gaoshenpan  show navigationbar end*/
	/**
	 * @param cb
	 */
	public TpTestItem(JCtrlCallback cb) {
		super(cb);
		// TODO Auto-generated constructor stub
	}

	/**
	 * 
	 */
	public TpTestItem() {
		// TODO Auto-generated constructor stub
	}
	
	/* (non-Javadoc)
	 * @see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.tp_test, container, false);
		mContext = Config.GetActivity().getApplicationContext();
		mStorageManager = mContext.getSystemService(StorageManager.class);
	      volumes = mStorageManager.getVolumes();
        mTestResult = (TextView) rootView.findViewById(R.id.test_result);
        mButton1 = (Button) rootView.findViewById(R.id.button1);
		mButton2 = (Button) rootView.findViewById(R.id.button2);
		mButton1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(6, 'P');
					} else {
						rewriteOneByteOfNv2499(37, 'P');
					}
				}
				 testFinish(true, 1, true);
				
			}
		});
		mButton2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(Config.CURR_PROJECT.isAuto()){
					if (!Config.ageingTested) {
						rewriteOneByteOfNv2499(6, 'F');
					} else {
						rewriteOneByteOfNv2499(37, 'F');
					}
				}
				testFinish(false, 1, false);
				
			}
		});
        Log.d(TAG, "batteryLevelSuccess----->true"+"oncreat");
//        startTest();
        return rootView;
	}
	
	private String getSdPath(){
		String pth = "storage/";
		   if (volumes != null) {
		         Collections.sort(volumes, VolumeInfo.getDescriptionComparator());
		         for (VolumeInfo vol : volumes) {
		            if (vol.getType() == VolumeInfo.TYPE_PUBLIC) {
		               mVolume = vol;
		            }
		         }
		        if(mVolume !=null){
		         if (mVolume.isMountedReadable()) {
		            // TODO: move statfs() to background thread
		            final File path = mVolume.getPath();
		            SD_CARD_PATH = path.getPath();
		            pth = SD_CARD_PATH;
		           } 
		        }
		      }
		return pth;
	}
	
	/* (non-Javadoc)
	 * @see android.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
        /*15-12-09 gaoshenpan fix full screen not show navigationbar begin*/
        hideNavigationBar();
        Settings.Global.putInt(Config.GetActivity().getContentResolver(), "mmi_test_fullscreen", 1);
        getSdPath();
		mTestResult.setText(getString(R.string.read_tp));
		isTpOk();
         
	}
	
	private boolean isTpOk() {
		Log.d(TAG, "batteryLevelSuccess----->true"+"startTest");
		new Thread(new Runnable() {

				@Override
			public void run() {
				// TODO Auto-generated method stub
					try {
//						wait(2000);
						int code = -4;
						OpenShortCheck.setIniFindDir(SD_CARD_PATH);
						OpenShortCheck.setDataSaveDir(SD_CARD_PATH);
						int ret = OpenShortCheck.openNode();
						if(ret > 0) {
							code = OpenShortCheck.openShortTest();
							int result = code == 0 ? R.string.tp_pass : R.string.tp_fail;
							Message msg = Message.obtain(mHandler, 0);
							msg.arg1 = result;
							mHandler.sendMessage(msg);
							Log.d(TAG, "Test Result: " + code);
							OpenShortCheck.closeNode();
						} else {
							Log.d(TAG, "OpenShortTest openNode() failed!(" + ret + ")");
						}
					} catch (Exception e) {
						// TODO: handle exception
						Log.d(TAG, "OpenShortTest openNode() exception" + e.toString());
					}
					
			}
			}).start();
		return true;
	}
	
	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
		Log.d(TAG, "----->onDetach()");
        mHandler.removeMessages(0);
	}
	@Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        Log.d(TAG, "----->onPause()");
        mHandler.removeMessages(0);
        Config.GetActivity().getWindow().getDecorView()
        .setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        Settings.Global.putInt(Config.GetActivity().getContentResolver(), "mmi_test_fullscreen", 0);
    }
	    
	    public static String readFile(String filePath){   
			String res="";   
			try{   
				BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath))));
				String str=null;
				while((str=br.readLine())!=null){
					res+=str;
				}  
	        }   
			catch(Exception e){   
	         e.printStackTrace();   
	        }   
	        return res;   
		}  
	    @Override
	    public boolean dispatchKeyEvent(KeyEvent event) {
	        // TODO Auto-generated method stub
	        return true;
	    }

}
